package com.zwh.pdf;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.zwh.entity.TbContractPlanItemDto;
import com.zwh.entity.TbContractPlanVo;
import org.springframework.cglib.beans.BeanMap;

import java.io.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zwh
 * @date 2024/3/25 0:23
 */
public class PdfService {

    public static void main(String[] args) throws Exception {
        PdfService pdfService = new PdfService();
//        FieldVo vo = new FieldVo();
//        vo.setName("hahah");
//        vo.setSex("1");
//        vo.setHome("home1");

//        pdfService.generateTempPDF(vo);

        pdfService.testTemplate();
    }

    public void testTemplate() throws IOException {
        PdfReader reader = null;
        PdfStamper ps = null;
        OutputStream fos = null;
        ByteArrayOutputStream bos = null;
        InputStream fin = null;
        FileOutputStream out = new FileOutputStream("F:/test3333.pdf");
        try {
            String fileName = "C:\\Users\\doubleZhang\\Downloads\\aa2.pdf";
            reader = new PdfReader(fileName);
            bos = new ByteArrayOutputStream();
            ps = new PdfStamper(reader, bos);

            // 使用中文字体(具体填入模板的字体在Adobe Acrobat软件中可以设置)
            BaseFont bf = BaseFont.createFont("/data/SIMSUN.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
            fontList.add(bf);
            AcroFields fields = ps.getAcroFields();
            fields.setSubstitutionFonts(fontList);


            fillData(fields, getData()); //填充模板

            //必须要调用这个，否则文档不会生成的
            ps.setFormFlattening(true);
            if(ps != null){
                ps.close();
            }
            //生成pdf路径存放的路径
            fos = out;
            fos.write(bos.toByteArray());

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(fos!=null){
                fos.flush();
                fos.close();
            }
            if (bos != null){
                bos.close();
            }
            if(reader != null){
                reader.close();
            }
        }
    }

    private Map<String, String> getData(){
        TbContractPlanVo vo = new TbContractPlanVo();
        vo.setProjectName("测试项目名称20240321");
        vo.setProCode("测试项目编号-20240321");
        vo.setSupervisionDepartment("监理项目部名称");
        List<TbContractPlanItemDto> itemDtoList = new ArrayList<>();
        for(int i = 0; i < 5; i++) {
            TbContractPlanItemDto dto = new TbContractPlanItemDto();
            dto.setSerialNumber((long) (i+1));
            dto.setSubcontractRang("分包范围"+i);
            dto.setSubcontractContent("分包工作量"+i);
            dto.setSubcontractType("劳务分包");
            dto.setProcurementMode("分包采购方式"+i);
            dto.setItemAmount(new BigDecimal("10.3569").multiply(new BigDecimal(i+1)));
            itemDtoList.add(dto);
        }
        vo.setItems(itemDtoList);
        Map<String, String> data = JSONObject.parseObject(JSONObject.toJSONString(vo), new TypeReference<Map<String, String>>(){});
        data.put("no1", "1");
        data.put("subcontractRang1", "subcontractRang1subcontractRang1");
        data.put("subcontractContent1", "subcontractContent1subcontractContent1");
        data.put("subcontractType1", "subcontractType1subcontractType1");
        data.put("procurementMode1", "procurementMode1procurementMode1");

        return data;
    }

    public  void generateTempPDF(FieldVo fieldVo) throws Exception {
        PdfReader reader = null;
        PdfStamper ps = null;
        OutputStream fos = null;
        ByteArrayOutputStream bos = null;
        InputStream fin = null;
        FileOutputStream out = new FileOutputStream("D:/test.pdf");
        try {
            String fileName = "D:/SourceCode/itext7pdf-edu/data/test01.pdf";
            //模板绝对路径--服务器
//            String fileName = "/app/file/pdf/KDDLR_Receipt_Template.pdf";
            reader = new PdfReader(fileName);
            bos = new ByteArrayOutputStream();
            ps = new PdfStamper(reader, bos);

            // 使用中文字体(具体填入模板的字体在Adobe Acrobat软件中可以设置)
            BaseFont bf = BaseFont.createFont("/data/SIMSUN.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
            fontList.add(bf);

            AcroFields fields = ps.getAcroFields();
            fields.setSubstitutionFonts(fontList);
            fillData(fields, data(fieldVo)); //填充模板

            //必须要调用这个，否则文档不会生成的
            ps.setFormFlattening(true);
            if(ps != null){
                ps.close();
            }
            //生成pdf路径存放的路径
            fos = out;
            fos.write(bos.toByteArray());

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(fos!=null){
                fos.flush();
                fos.close();
            }
            if (bos != null){
                bos.close();
            }
            if(reader != null){
                reader.close();
            }
        }
    }

    /**
     * 填充模板中的数据
     */
    public void fillData(AcroFields fields, Map<String, String> data) {
        try {
            for (String key : data.keySet()) {
                String value = data.get(key);
                // 为字段赋值,注意字段名称是区分大小写的
                fields.setField(key, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 填充数据源
     * 其中data存放的key值与pdf模板中的文本域值相对应
     */
    public Map<String, String> data(FieldVo fieldVo){
        // 构造数据 , key要与模板中的别名一一对应
        Map<String, String> paramters = new HashMap<>();
        paramters.put("name",fieldVo.getName());
        paramters.put("sex",fieldVo.getSex());
        paramters.put("home",fieldVo.getHome());
        return paramters;
    }
}

